#include "EventLoopThreadPool.h"
#include"EventLoopThread.h"

#include<memory>

EventLoopThreadPool::EventLoopThreadPool(EventLoop *baseLoop, const std::string &nameArg)
    : baseLoop_(baseLoop)
    , name_(nameArg)
    , started_(false)
    , numThreads_(0)
    , next_(0) 
{
}
EventLoopThreadPool::~EventLoopThreadPool(){//所有绑定的loop都是栈上对象无需析构
}



void EventLoopThreadPool::start(const ThreadInitCallback &cb)
{
    started_ = true;
    for(int i = 0; i < numThreads_; ++i)
    {
        char buf[name_.size() + 32];
        snprintf(buf, sizeof buf, "%s%d", name_.c_str(), i);
        EventLoopThread* t = new EventLoopThread(cb, buf);
        threads_.push_back(std::unique_ptr<EventLoopThread>(t));
        loops_.push_back(t->startLoop()); //底层创建的线程，绑定一个新的EventLoop，并返回EventLoop指针
    }

    //如果不设置线程数量，只有一个baseloop
    if(numThreads_ == 0 && cb)
    {
        cb(baseLoop_);
    }
}

// 如果在多线程，baseloop以轮询方式分类channel给subloop
EventLoop *EventLoopThreadPool::getNextLoop()
{
    EventLoop* loop = baseLoop_;

    if(!loops_.empty())
    {
        loop = loops_[next_];
        ++next_;
        if(next_ >= loops_.size())
        {
            next_ = 0;
        }
    }

    return loop;
}

std::vector<EventLoop *> EventLoopThreadPool::getAllLoops()
{
    if(loops_.empty())
    {
        return std::vector<EventLoop*>(1, baseLoop_);
    }
    return loops_;
}